import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import Company from 'src/entities/company.entity';
import Student from 'src/entities/student.entity';
import User from 'src/entities/user.entity';
import { Repository } from 'typeorm';
import {
  AccountListDto,
  BatchCreateAccountDto,
  CreateAccountDto,
  UpdateAccountDto,
} from './account.dto';
import { isEmpty } from 'lodash';
import { ApiException } from 'src/core/exceptions/api.exception';

@Injectable()
export class AccountService {
  constructor(
    @InjectRepository(User) private userRepository: Repository<User>,
    @InjectRepository(Student) private studentRepository: Repository<Student>,
    @InjectRepository(Company) private companyRepository: Repository<Company>,
  ) {}

  // 查询账号列表
  async find(query: AccountListDto) {
    const { page, size, nickname, username, role } = query;

    const queryBuilder = this.userRepository
      .createQueryBuilder('user')
      .select([
        'user.id',
        'user.nickname',
        'user.username',
        'user.role',
        'user.avatar',
        'user.enableStatus',
        'user.createdAt',
      ])
      .skip(size * (page - 1))
      .take(size);

    if (nickname !== undefined) {
      queryBuilder.andWhere('user.nickname Like :nickname', { nickname: `%${nickname}%` });
    }

    if (username !== undefined) {
      queryBuilder.andWhere('user.username Like :username', { username: `%${username}%` });
    }

    if (role !== undefined) {
      queryBuilder.andWhere('user.role = :role', { role });
    }

    const [list, count] = await queryBuilder.getManyAndCount();
    return { list, count };
  }

  // 添加账号
  async create(data: CreateAccountDto) {
    const user = await this.userRepository.findOne({ where: { username: data.username } });
    if (!isEmpty(user)) {
      throw new ApiException(10015);
    }

    const saveUser = this.userRepository.create({
      ...data,
      nickname: data.username,
      avatar: 'https://recruit-1307438078.cos.ap-guangzhou.myqcloud.com/avatar/default.jpg',
    });
    const newUser = await this.userRepository.save(saveUser);

    // 学生身份
    if (data.role === 'student') {
      const student = { userId: newUser.id, name: '', birth: '', sex: '', major: '', college: '' };
      await this.studentRepository.save(student);
    } else {
      // 企业身份
      const company = this.companyRepository.create({
        userId: newUser.id,
        logo: 'https://recruit-1307438078.cos.ap-guangzhou.myqcloud.com/logo/default.png',
        name: '',
        fullName: data.username,
        industryId: null,
        nature: '',
        scale: '',
        welfare: '',
        workTime: '',
        weekend: '',
        workOvertime: '',
        address: '',
        introduce: '',
      });
      await this.companyRepository.save(company);
    }
  }

  // 更新账号
  async update(data: UpdateAccountDto) {
    const user = await this.userRepository.findOne({ where: { id: data.id } });
    if (isEmpty(user)) {
      throw new ApiException(10005);
    }

    const updateUser = this.userRepository.merge(user, data);
    await this.userRepository.save(updateUser);
  }

  // 批量添加账号
  async batch(data: BatchCreateAccountDto) {
    const repeat: string[] = [];
    const nonRepeatItems: CreateAccountDto[] = [];
    const userList = await this.userRepository.find({ select: ['username'] });

    // 将重复的账号提取出来
    data.list.forEach((item) => {
      const exists = userList.some((user) => user.username === item.username);
      if (exists) {
        repeat.push(item.username);
      } else {
        nonRepeatItems.push(item);
      }
    });

    const accountPromise = nonRepeatItems.map(async (item) => {
      // 注册用户
      const newUser = this.userRepository.create({
        ...item,
        nickname: item.username,
        avatar: 'https://recruit-1307438078.cos.ap-guangzhou.myqcloud.com/avatar/default.jpg',
      });
      const user = await this.userRepository.save(newUser);

      // 注册学生
      if (item.role === 'student') {
        const student = { userId: user.id, name: '', birth: '', sex: '', major: '' };
        await this.studentRepository.save(student);
      } else {
        // 注册企业
        const company = this.companyRepository.create({
          userId: user.id,
          logo: 'https://recruit-1307438078.cos.ap-guangzhou.myqcloud.com/logo/default.png',
          name: '',
          fullName: item.username,
          industryId: null,
          nature: '',
          scale: '',
          welfare: '',
          workTime: '',
          weekend: '',
          workOvertime: '',
          address: '',
          introduce: '',
        });
        await this.companyRepository.save(company);
      }
    });

    await Promise.all(accountPromise);
    return repeat;
  }
}
